//当前筛选的产品线 0 蜜哆哆 1 蜜雅阁 2 品牌馆，默认为蜜雅阁
var curGoodsType = 0;

//当前筛选分组
var curGroupId;

//当前筛选的商品状态
var curStatus;

//当前编辑商品id
var curEditId;

// var editThumbUrl;
//未删除、待删除的图片url Arr
var originalPicUrlArr = [];


//上传修改的图片
var editPicUrlArr = [];

//主图缩略图url
var editThumbUrl = "";

//refer to Java Arraylist blah modCount
var modCount = new Object();

var modDetailCount = new Object();

var origGoodsIntroduce = "";

var $table = $("#goods_list_table");

//dropzone instance
var myDropzone;

var goodsThumbDropzone;
$(function () {
    initTable($table);
    //生成分组下拉框
    executeGetFirstSecGroup(curGoodsType);
    initDropzone();
    //详情说明
    initGoodsIntroduceSummernote("goodsIntroduce");
    //显示邮费方案
    showPostagePlans();
});

function initDropzone() {
    Dropzone.autoDiscover = false;//解决两次实例Dropzone错误，可在控制台看到该错误
// Dropzone class:
    myDropzone = new Dropzone("div#editPic",
        {
            url: urlcore + "/api/attachment/upload",
//                                        paramName: "skuUrl", // The name that will be used to transfer the file
            maxFiles: 7,
            thumbnailWidth: 120,
            thumbnailHeight: 120,
            addRemoveLinks: true,//清除图片
            dictRemoveFile: "删除图片",//如果addRemoveLinks为 true，这段文本用来设置删除文件显示文本.
            dictCancelUpload: "取消上传",//如果addRemoveLinks为 true，这段文本用来设置取消上载链接的文本
            previewsContainer: "#editPic-pre", // 文件预览显示位置,可以为id或class选择器或html元素
            success: function (file, data) {
                //这里的$(this)其实得到的是Dropzone对象（对象数组，取第一个为当前Dropzone对象）
                console.log($(this));
                //通过查看Dropzone对象的结构得到对应div的id
                console.log("file:", file);
                console.log("data:", data);
                var curPicUrl = data.data[0];
                //重要！！为file对象添加一个url属性，将上传完成的图片url加到该属性值中，之后的removeFile和从待上传url数组中删除都依赖这个操作
                file.url = curPicUrl;
                console.log(file);
                //放进数组中
                editPicUrlArr.push(curPicUrl);
                console.log("editPicUrlArr :", editPicUrlArr);
            },
            init: function () {
                this.on("addedfile", function (file) {
                    console.log("addedfile");// actions...

                });
                this.on("removedfile", function (file) {
                    //从数组中移除url,因移除的file必然先存在，所以无需判断indexOf为-1
                    editPicUrlArr.splice(editPicUrlArr.indexOf(file.url), 1);
                    console.log("editPicUrlArr:", editPicUrlArr);
                    console.log("removedfile", file);// actions...
                });
            }
        });

    //商品主图修改
    goodsThumbDropzone = new Dropzone("div#editThumbPic",
        {
            url: urlcore + "/api/attachment/upload",
//                                        paramName: "skuUrl", // The name that will be used to transfer the file
            maxFiles: 1,
            thumbnailWidth: 120,
            thumbnailHeight: 120,
            addRemoveLinks: true,//清除图片
            dictRemoveFile: "删除图片",//如果addRemoveLinks为 true，这段文本用来设置删除文件显示文本.
            dictCancelUpload: "取消上传",//如果addRemoveLinks为 true，这段文本用来设置取消上载链接的文本
            dictMaxFilesExceeded: "上传数量已达上限",
            previewsContainer: "#editThumbPic-pre", // 文件预览显示位置,可以为id或class选择器或html元素
            success: function (file, data) {
                //这里的$(this)其实得到的是Dropzone对象（对象数组，取第一个为当前Dropzone对象）
                console.log($(this));
                //通过查看Dropzone对象的结构得到对应div的id
                var sku_url_id = '#' + $(this)[0].element.id;
                console.log("file:", file);
                console.log("data:", data);
                editThumbUrl = data.data[0];
                //重要！！为file对象添加一个url属性，将上传完成的图片url加到该属性值中，之后的removeFile和从待上传url数组中删除都依赖这个操作
                file.url = editThumbUrl;
                console.log(file);
                //放进数组中
            },
            init: function () {
                this.on("addedfile", function (file) {
                    console.log("addedfile");// actions...
                    /*        file.previewElement.addEventListener("click", function () {
                                goodsThumbDropzone.removeFile(file);
                            });*/

                });
                this.on("maxfilesexceeded", function (file) {
                    if (editThumbUrl != "") {
                        goodsThumbDropzone.removeFile(file);
                        alert("已达上传数量上限");
                    }
                });
                this.on("removedfile", function (file) {
                    if (file.url != undefined && file.url == editThumbUrl) {
                        editThumbUrl = "";
                    }
                    //从数组中移除url,因移除的file必然先存在，所以无需判断indexOf为-1
                    console.log("removedfile", file);// actions...
                });
            }
        });

}

//更换产品线
$("#goodsType").on("change", function () {
    curGoodsType = $("#goodsType").val();
    /*    //一级分组列表
        firstGroupArr = [];
        //二级分组
        secondGroupArr = [];
        $("#curGroup").html("");
        //获取一二级分组（分开）
        executeGetFirstSecGroup(curGoodsType);*/
    $table.bootstrapTable("refresh");
});

//分组改变，在管理分组商品时刷新列表
$("#curGroup").change(function () {
    curGroupId = $("#curGroup").val();
    $table.bootstrapTable("refresh");
});

//更换筛选状态
$("#curStatus").on("change", function () {
    curStatus = $("#curStatus").val();
    $table.bootstrapTable("refresh");
});

//刪除
function doDelete(id) {
    confirm("该商品下可能还有多件商品,删除后会使含有该商品的未发货订单不能显示商品，确认删除吗？", function (callback) {
        if (callback) {
            delGoods();
        }
    });

    function delGoods() {
        $.ajax({
            type: "GET",
            url: urlcore + "/api/goods/deleteGoodsOne?id=" + id,
            dataType: "json",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: {},
            success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
                if (data.success == true) {
                    $table.bootstrapTable("refresh");
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                alert("删除失败");
            }
        });
    }

}


//批量 1上架 2下架
function changeStatusBatch(tag) {
    var uptGoodsArr = [];
    var selection = $table.bootstrapTable('getSelections');
    if (selection.length == 0) {
        alert("请先选择商品");
        return;
    }
    var targetStatus = "";
    if (tag == 1) {
        targetStatus = 2;
        uptStaBatch();
    }

    if (tag == 2) {
        confirm("确认下架多个商品吗", function (callback) {
            if (callback) {
                targetStatus = 3;
                uptStaBatch();
            }
        });
    }

    function uptStaBatch() {
        for (var item of selection) {
            uptGoodsArr.push({
                id: item.id,
                goodsStatus: targetStatus
            })
        }

        $.ajax({
            url: urlcore + "/api/goods/uptGoodsBatch",
            type: "post",
            dataType: "json",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: JSON.stringify(uptGoodsArr),
            success: function (cbdata) {
                if (tag == 2)
                    alert("批量下架成功");
                $table.bootstrapTable("refresh")
            },
            error: function (cbdata) {
                alert("更新状态失败");
            }
        })
    }


}

//更改商品状态
function changgeToStatus(id, targetStatus, isBatch) {
    if (targetStatus == 3) {
        confirm("确认下架该商品吗", function (callback) {
            if (callback) {
                uptStatus();
            }
        });
    }

    if (targetStatus != 3)
        uptStatus();

    function uptStatus() {
        $.ajax({
            url: urlcore + "/api/goods/update",
            type: "post",
            dataType: "json",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: JSON.stringify({
                id: id,
                goodsStatus: targetStatus
            }),
            success: function (cbdata) {
                $table.bootstrapTable("refresh")
            },
            error: function (cbdata) {
                alert("更新状态失败");
            }
        })
    }
}


//编辑商品信息和图片
function editGoods(id) {
    curEditId = id;
//要先设置bootstrap-table中的uniqueId: "id",得到该行原始数据
    var originalData = $table.bootstrapTable('getRowByUniqueId', id);
    console.log(originalData);
    //主图
    $("#origThumbPicDiv").height(125);
    editThumbUrl = originalData.goodsUrl;
    var origThumbPicHtml = "";
    origThumbPicHtml += "<div style='float: left'> <img class='oriImage' src=\"" + originalData.goodsUrl + "\"></div>";
    $("#origThumbPic").html(origThumbPicHtml);
    modDetailCount.modSumCount = 0;
    modCount.modSumCount = 0;
    modCount.modGoodsName = 0;
    modCount.modMPrice = 0;
    modCount.modreturnRate = 0;
    modCount.modreturnRateY = 0;
    modCount.modPostage = 0;
    modCount.modrainbowOnly = 0;
    $("#editModalGoodsName").val(originalData.goodsName);
    $("#editModalMPrice").val(originalData.mPrice);
    $("#editModalOtherPrice").val(originalData.otherPrice);
    $("#editModalReturnRate").val(originalData.returnRate);
    $("#editModalReturnRateY").val(originalData.returnRatey);
    if (null != originalData.postage) {
        $("#postage").val(originalData.postage);
    }
    $("#editModalOverDeliveryPostage").val(originalData.overDeliveryPostage);
    $("#editModalGtOnePostage").val(originalData.gtOnePostage);
    $("input[type='radio'][name='rainbow_only'][value='" + originalData.rainbowOnly + "']").prop("checked", "checked");
    $.ajax({
        url: urlcore + "/api/goodsDetail/getGoodsDetailByGoodsId",
        method: "get",
        dataType: "json",
        data: {goodsId: id},
        contentType: "application/json;charset=utf-8",
        success: function (cbdata) {
            if (undefined != cbdata.data.goodsIntroduce || null != cbdata.data.goodsIntroduce) {
                $('#goodsIntroduce').summernote('code', cbdata.data.goodsIntroduce);
                origGoodsIntroduce = $('#goodsIntroduce').summernote('code');
                console.log("summernote:", origGoodsIntroduce)
            }
            //init detail pic's modCount`
            modCount.modDetailPic = 0;
            console.log(cbdata);
            originalPicUrlArr = cbdata.data.picturesUrl.split(",");
            if (originalPicUrlArr.length > 0) {
                var origPicDivHeight = originalPicUrlArr.length % 4 == 0 ? (originalPicUrlArr.length / 4) * 125 : (originalPicUrlArr.length / 4 + 1) * 125;
                $("#origPicDiv").height(origPicDivHeight);
                var origPicHtml = "";
                for (var tempUrl of originalPicUrlArr) {
                    origPicHtml += "<div style='float: left'><div> <img class='oriImage' src=\"" + tempUrl + "\"></div>" +
                        "<a  href=\"javascript:undefined;\" onclick='rmPic(this)' data-dz-remove=\"\">删除图片</a>" +
                        "</div>";

                }
                $("#origPic").html(origPicHtml);
            }
            console.log(originalPicUrlArr);
        },
        error: function (data) {
            alert("获取详情失败");
        }


    });
}

function rmPic(e) {
    confirm("确认删除该图片吗？", function (callback) {
        if (callback) {
            delPicViaDetail();
        }
    });

    function delPicViaDetail() {
        var $e = $(e);
        var img = $e.prev().children().eq(0);
        var rmDiv = $e.parent();
        var imgUrl = img.attr('src');
        originalPicUrlArr.splice(originalPicUrlArr.indexOf(imgUrl), 1);
        var editedUrls = originalPicUrlArr.join(',');
        console.log(originalPicUrlArr);
        console.log("imgUrl:", imgUrl);
        console.log("editedUrls:", editedUrls);
        $.ajax({
            url: urlcore + "/api/goodsDetail/update",
            type: "post",
            dataType: "json",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: JSON.stringify({
                goodsId: curEditId,
                picturesUrl: editedUrls

            }),
            success: function (cbdata) {
                rmDiv.remove();
            },
            error: function (cbdata) {
                alert("更新状态失败");
            }
        });
    }
}

//保存更改
function saveEditGoods() {
    var modGoods = new Object();
    var modGoodsDetail = new Object();
    var originalData = $table.bootstrapTable('getRowByUniqueId', curEditId);
    if (originalData.goodsName != $("#editModalGoodsName").val()) {
        modCount.modGoodsName = 1;
    }
    if (originalData.mPrice != $("#editModalMPrice").val()) {
        modCount.modMPrice = 1;
    }
    if (originalData.otherPrice != $("#editModalOtherPrice").val()) {
        modCount.modOtherPrice = 1;
    }
    if (originalData.goodsUrl != editThumbUrl) {
        modCount.modGoodsUrl = 1;
    }
    if (originalData.returnRate != $("#editModalReturnRate").val()) {
        modCount.modreturnRate = 1;
    }
    if (originalData.returnRatey != $("#editModalReturnRateY").val()) {
        modCount.modreturnRateY = 1;
    }
    if (originalData.postage != $("#postage").val()) {
        modCount.modPostage = 1;
    }
    if (originalData.overDeliveryPostage != $("#editModalOverDeliveryPostage").val()) {
        modCount.modOverDeliveryPostage = 1;
    }
    if (originalData.gtOnePostage != $("#editModalGtOnePostage").val()) {
        modCount.modGtOnePostage = 1;
    }
    if (originalData.rainbowOnly != $("input[type='radio'][name='rainbow_only']:checked").val()) {
        console.log("origirainbow:", originalData.rainbowOnly);
        console.log("inputrainbow:", $("input[type='radio'][name='rainbow_only']:checked").val());
        modCount.modrainbowOnly = 1;
    }
    var goodsIntroduce = $('#goodsIntroduce').summernote('code');
    if (origGoodsIntroduce != "" && origGoodsIntroduce != goodsIntroduce) {
        modDetailCount.modGoodsIntroduce = 1;
    }


    if (modCount.modGoodsName == 1) {
        modGoods.goodsName = $("#editModalGoodsName").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modMPrice == 1) {
        modGoods.mPrice = $("#editModalMPrice").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modOtherPrice == 1) {
        modGoods.otherPrice = $("#editModalOtherPrice").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modGoodsUrl == 1) {
        modGoods.goodsUrl = editThumbUrl;
        modCount.modSumCount += 1;
    }
    if (modCount.modreturnRate == 1) {
        modGoods.returnRate = $("#editModalReturnRate").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modreturnRateY == 1) {
        modGoods.returnRatey = $("#editModalReturnRateY").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modPostage == 1) {
        modGoods.postage = $("#postage").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modOverDeliveryPostage == 1) {
        modGoods.overDeliveryPostage = $("#editModalOverDeliveryPostage").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modGtOnePostage == 1) {
        modGoods.gtOnePostage = $("#editModalGtOnePostage").val();
        modCount.modSumCount += 1;
    }
    if (modCount.modrainbowOnly == 1) {
        modGoods.rainbowOnly = $("input[type='radio'][name='rainbow_only']:checked").val();
        modCount.modSumCount += 1;
    }
    if (modDetailCount.modGoodsIntroduce == 1) {
        modGoodsDetail.goodsIntroduce = goodsIntroduce;
        modDetailCount.modSumCount += 1;
        origGoodsIntroduce = "";
    }


    // if (originalPicUrlArr.toString() != editPicUrlArr.toString()) {
    if (editPicUrlArr.length > 0) {
        modCount.modDetailPic = 1;
    }
    if (modCount.modDetailPic == 1) {
        modDetailCount.modSumCount += 1;
        //详情多张轮播图url拼接
        var curDetailGoodsUrl = editPicUrlArr.join(",");
        modGoodsDetail.picturesUrl = curDetailGoodsUrl;
    }
    //check modify
    if (modCount.modSumCount == 0 && modDetailCount.modSumCount == 0)
        return;
    modifyDetailPic();

    function modifyDetailPic() {
        if (modCount.modSumCount > 0) {
            modGoods.id = curEditId;
            //修改商品基本信息
            $.ajax({
                url: urlcore + "/api/goods/update",
                type: "post",
                dataType: "json",
                headers: {"Content-Type": "application/json;charset=UTF-8"},
                data: JSON.stringify(modGoods),
                success: function (cbdata) {
                    alert("修改成功");
                    $table.bootstrapTable("refresh");
                    //移除模态框dropzone中旧图
                    goodsThumbDropzone.removeAllFiles(true);
                    $("#editModal input").val("");
                    modCount = new Object();
                    editThumbUrl = "";
                },
                error: function (cbdata) {
                    alert("更新状态失败");
                }
            });
        }
        if (modDetailCount.modSumCount > 0) {
            modGoodsDetail.goodsId = curEditId;
            $.ajax({
                url: urlcore + "/api/goodsDetail/update",
                type: "post",
                dataType: "json",
                headers: {"Content-Type": "application/json;charset=UTF-8"},
                data: JSON.stringify(modGoodsDetail),
                success: function (cbdata) {
                    $table.bootstrapTable("refresh");
                    //移除模态框dropzone中旧图
                    myDropzone.removeAllFiles(true);
                    editPicUrlArr = [];
                    originalPicUrlArr = [];
                    modDetailCount = new Object();
                    $("#editModal input").val("");
                },
                error: function (cbdata) {
                    alert("更新状态失败");
                }
            });
        }
    }
}

//cancel edit
function cancelEditGoods() {
    $("#editModal input").val("");
    goodsThumbDropzone.removeAllFiles(true);
    myDropzone.removeAllFiles(true);
    $("#origThumbPic").html("");
    $("#origPic").html("");
    editThumbUrl = "";
    editPicUrlArr = [];
    originalPicUrlArr = [];
    modCount = new Object();
}


var columns = [
    {
        checkbox: true,
    }, {
        title: "序号",
        align: "center",
        valign: "middle",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "商品ID",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
    }, {
        field: "goodsName",
        title: "商品名称",
        halign: "center",
        valign: "middle",
        sortable: true
    }, {
        field: "mPrice",
        title: "商品价格",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        sortable: true
    }, {
        field: "goodsUrl",
        title: "商品图片",
        align: "center",
        valign: "middle",
        width: "70px",
        formatter: function (value, row, index) {
            return '<img style="width: 50px;height: auto" src="' + value + '" >';
        }
    }, {
        field: "returnRate",
        title: "哆币返现比",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "100px"
    }, {
        field: "returnRatey",
        title: "雅币返现比",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "100px"
    }, {
        field: "gtOnePostage",
        title: "邮费显示名称",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
    }, {
        field: "goodsStatus",
        title: "商品状态",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            return convertGoodsStatus(value, 0);
        }
    }, {
        field: "gmtDatetime",
        title: "上传时间",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "100px",
    }, {
        title: "操作",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "150px",
        formatter: function (value, row, index) {
            var optHtml = "\t\t\t<a class=\"btn btn-default btn-xs\" href=\"javascript:;\" onclick=\"editGoods(" + row.id + ")\" data-toggle=\"modal\" data-target=\"#editModal\"> 详细/修改</a>\n" +
                // "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_details.html?id=" + row.id + "\"> 详细</a>\n" +
                "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_recommend.html?id=" + row.id + "\"> 商品推荐</a>\n" +
                convertGoodsStatus(row.goodsStatus, 1, row.id) +
                "\t\t\t<a class=\"btn btn-danger btn-xs\" href=\"javascript:;\" onclick=\"doDelete(" + row.id + ")\"> 删除</a>\n";
            return optHtml;
        }
    }];


var queryParams = function (params) {
    console.log("params:", params);
    var param = {
        goods: {
            goodsType: curGoodsType,
            indexGroupId: curGroupId,
            goodsStatus: curStatus,
        },
        page: {
            offset: params.offset,
            current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
            size: params.limit
        },
        searchText: params.search
    };

    return param;
};

//初始化表格 tableins:表格实例 ,
function initTable(tableins) {
    tableins.bootstrapTable({
        columns: columns,
        method: "post",
        url: urlcore + "/api/goods/getAllPageableGoods",
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                console.log(records);
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        uniqueId: "id",
        // toolbar: '#toolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 16,//每页大小
        pageList: [16, 32, 48, 64],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        // clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//默认为客户端搜索，服务器端接收params中的searchText后可以做服务器端搜索
        // searchText:"",//初始搜索文本
    });
}


//转化产品线
function convertSourceType(value) {
    var result;
    if (value == 0) {
        result = "蜜哆哆";
    } else if (value == 1) {
        result = "蜜雅阁";
    }
    return result;
}


//转化商品状态
function convertGoodsStatus(value, returnTag, id) {
    var goodsStatus = value;
    var goodsStatusShow = "";
    var changgeStatusOptBtn = "";
    if (goodsStatus == 1) {
        goodsStatusShow = "尚未发布";
        changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-success btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 发布上架</a>\n";
    } else if (goodsStatus == 2) {
        goodsStatusShow = "已发布上架";
        changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-info btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "3" + ")\"> 下架</a>\n";

    } else if (goodsStatus == 3) {
        goodsStatusShow = "已下架";
        changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-success btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 重新上架</a>\n";
    } else {
        goodsStatusShow = "";
        changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-success btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 发布上架</a>\n";
    }
    //表示返回状态名
    if (returnTag == 0) {
        return goodsStatusShow;
    }
    if (returnTag == 1)
        return changgeStatusOptBtn;
}


/**
 * 原列表代码
 */
/*$(document).ready(function () {
    var type = getvl("goodsType") == "" ? 0 : getvl("goodsType");
    var select = document.getElementById("goods_type");
    for (var i = 0; i < select.length; i++) {
        if (select[i].value == type) {
            select[i].selected = true;
            break;
        }
    }
    init(type, callback, 1);
});*/


/*function init(type, callback, current) {
    $("#thislist").html("");
    if (type == null || type == undefined) {
        type = $('#goods_type option:selected').val();
    }
    $.ajax({
        type: "post",
        url: urlcore + "/api/goods/selectiveGoodsList?type=" + type + "&current=" + current + "&sid=",
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        data: {},
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            if (data.success == true) {
                callback(data.data.records);
                $('#thiscount').text(data.data.total);
                $("#pager").pager({
                    pagenumber: current,
                    pagecount: data.data.pages,
                    totalcount: data.data.total,
                    buttonClickCallback: PageClick
                });
            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "login.html";
                }
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert("上传失败");
        }
    });

}*/


/*//回调函数
PageClick = function (pageclickednumber) {
    var type = getvl("goodsType") == "" ? 0 : getvl("goodsType");
    init(type, callback, pageclickednumber);
};*/

/*var callback = function (data) {
    var html = "", goodsName = "", goodsType = "", goodsUrl = "", markerPrice = "", returnRate = "", returnRateY = "",
        goodsStatus = "", gmtDatetime = "", id = "";
    var goodsStatusShow = "";//显示的商品状态
    var changgeStatusOptBtn = "";
    for (var i = 0; i < data.length; i++) {
        id = data[i].id;
        goodsName = data[i].goodsName;
        goodsUrl = data[i].goodsUrl != null ? data[i].goodsUrl : "";
        mPrice = data[i].mPrice;
        returnRate = data[i].returnRate;
        postage = data[i].postage;
        /!*邮费类型（1 江浙沪包邮 2  满九十九包邮 3  七块钱邮费  4 全国包邮（港澳台地区、西藏、新疆、内蒙古、宁夏、青海等地区除外））*!/
        if (postage == undefined) {
            postage = "";
        } else if (postage == 1) {
            postage = "江浙沪包邮";
        } else if (postage == 2) {
            postage = "满99包邮";
        } else if (postage == 3) {
            postage = "7块钱邮费"
        } else if (postage == 4) {
            postage = "全国包邮（港澳台地区、西藏、新疆、内蒙古、宁夏、青海等地区除外）";
        }
        returnRateY = data[i].returnRatey;
        goodsStatus = data[i].goodsStatus;

        if (goodsStatus == 1) {
            goodsStatusShow = "尚未发布";
            changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 发布上架</a>\n";
        } else if (goodsStatus == 2) {
            goodsStatusShow = "已发布上架";
            changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "3" + ")\"> 下架</a>\n";

        } else if (goodsStatus == 3) {
            goodsStatusShow = "已下架";
            changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 重新上架</a>\n";
        } else {
            goodsStatusShow = "";
            changgeStatusOptBtn = "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"changgeToStatus(" + id + "," + "2" + ")\"> 发布上架</a>\n";
        }
        gmtDatetime = data[i].gmtDatetime != null ? new Date(data[i].gmtDatetime).pattern("yyyy-MM-dd hh:mm:ss") : "";
        html += "  <tr id=\"" + id + "\">\n" +
            "  \t\t<td>" + (i + 1) + "</td>\n" +
            "  \t\t<td>" + id + "</td>\n" +
            "  \t\t<td>" + goodsName + "</td>\n" +
            "  \t\t<td>" + mPrice + "</td>\n" +
            "\t\t <td class=\"footable-visible\"><img width=\"40px\" height=\"40px\" src=\"" + goodsUrl + "\"></td>\n" +
            "  \t\t<th>" + returnRate + "</th>\n" +
            "  \t\t<th>" + returnRateY + "</th>\n" +
            "  \t\t<th>" + postage + "</th>\n" +
            "  \t\t<th>" + goodsStatusShow + "</th>\n" +
            "  \t\t<th>" + gmtDatetime + "</th>\n" +
            "  \t\t<td>\n" +
            // "  \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_add.html?id=" + id + "\"> 修改</a>\n" +
            "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"doDelete(" + id + ")\"> 删除</a>\n" +
            "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_details.html?id=" + id + "\"> 详细</a>\n" +
            "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_recommend.html?id=" + id + "\"> 商品推荐</a>\n" +
            changgeStatusOptBtn +
            "  \t\t</td>\n" +
            "  \t</tr>";
    }
    $("#thislist").append(html);
}*/

/*//搜索
function searchuser() {
    var type = $('#goods_type option:selected').val();//选中的值
    init(type, callback, 1);
}*/

function initGoodsIntroduceSummernote(summernoteId) {
    $('#' + summernoteId).summernote({
        // height: 200,
        minHeight: 400,
        maxHeight: 500,
        // focus: true,
        placeholder: '添加介绍...',
        lang: 'zh-CN',
        dialogsInBody: true,
        disableDragAndDrop: false,
        popover: {
            image: [
                // ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
                ['float', ['floatLeft', 'floatRight', 'floatNone']],
                ['remove', ['removeMedia']]
            ],
            link: [
                ['link', ['linkDialogShow', 'unlink']]
            ],
            air: [
                ['color', ['color']],
                ['font', ['bold', 'underline', 'clear']],
                ['para', ['ul', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']]
            ]
        },
        callbacks: {
            onImageUpload: function (files, editor, $editable) {
                sendFile(files, editor, $editable, summernoteId);
            },
            onFocus: function () {
                console.log('Editable area is focused');
                $("body").addClass("modal-open");
            },
            onBlur: function () {
                $("body").addClass("modal-open");
            },
            onPaste: function (e) {
                // alert('Called event paste');
                console.log(e);
            }
        }
    });
}

function sendFile(files, editor, $editable, summernoteId) {
    debugger
    var data = new FormData();
    for (var file of files) {
        data.append("file", file);
    }
    $.ajax({
        data: data,
        type: "POST",
        url: urlcore + "/api/attachment/upload", //图片上传出来的url，返回的是图片上传后的路径，http格式
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        success: function (cbdata) {//data是返回的hash,key之类的值,数组，key是定义的文件名
            if (cbdata.data.length > 0) {
                for (var cbFile of cbdata.data)
                    $('#' + summernoteId).summernote('insertImage', cbFile); // the insertImage API
                $("body").addClass("modal-open");
            }
        },
        error: function () {
            alert("上传失败");
        }
    });
}

//获取一二级分组（分开）
function executeGetFirstSecGroup(selectedGroupType) {
    $.ajax({
        url: urlcore + "/api/indexGroup/getAllGroup",
        method: "get",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: {
            groupType: selectedGroupType,
        },
        success: function (cbdata) {
            console.log(cbdata.data);
            firstGroupArr = cbdata.data.firstGroupList;
            secondGroupArr = cbdata.data.secondGroupList;
            //生成选择分组的optgroup
            generateOptgroupHtml(firstGroupArr, secondGroupArr);
        },
        error: function (data) {
            alert("获取分组失败");
        }
    });
}

//生成选择分组的optgroup
function generateOptgroupHtml(firstGroupArr, secondGroupArr) {

    var optgroupHtmlStr = "";
    //生成optgroup
    for (var item of firstGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 0);
        optgroupHtmlStr += htmlStr;
    }
    $("#curGroup").append(optgroupHtmlStr);

    //生成optgroup的option
    for (var item of secondGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 1);
        var parentId = item.pid;
        $("#curGroup").find('optgroup[data-id="' + parentId + '"]').append(htmlStr);
    }
}

//生成分组选择框的optgroup（tag为0）或option（tag为1）
function getGroupOptionHtml(item, tag) {
    var htmlStr = "";
    if (tag == 0) {
        htmlStr = "   <optgroup data-id=\"" + item.id + "\" label=\"" + item.title + "\">\n" +
            "    </optgroup>";
    }
    if (tag == 1) {
        htmlStr = "<option value=\"" + item.id + "\">" + item.title + "</option>";
    }
    return htmlStr;
}

//去修改某个商品的规格价
function goModPrice() {
    window.location.href = "sku_list.html?goodsId=" + curEditId;
}

//显示邮费方案
function showPostagePlans() {
    $.ajax({
        url: urlcore + "/api/deliveryPlan/getGoodsAddChosenPlans",
        method: "get",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log(data.data);
            var items = data.data;
            if (items.length > 0) {
                //生成选择邮费方案的opt
                generateOptHtml(items);
            }
        },
        error: function (data) {
            alert("获取方案失败");
        }
    });
}

//生成选择分组的optgroup
function generateOptHtml(items) {
    var htmlStr = "";
    //生成optgroup
    for (var item of items) {
        htmlStr += "<option value=\"" + item.num + "\">" + item.title + "</option>";
    }
    $("#postage").append(htmlStr);
}